<?php

namespace app\models;

use app\common\utils\ArrayUtil;
use app\common\utils\QyWechat;
use Yii;

/**
 * This is the model class for table "gky_qyh_department".
 *
 * @property integer $id
 * @property integer $dno
 * @property string $name
 * @property integer $parentid
 * @property integer $order
 * @property integer $qyh_id
 *
 * @property GkyQyhDepartment $parent
 * @property GkyQyhDeptUser[] $deptUsers
 * @property GkyQyh $qyh
 */
class GkyQyhDepartment extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gky_qyh_department';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['dno', 'parentid', 'order','qyh_id'], 'integer'],
            [['id', 'name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'qyh_id' => 'QyhID',
            'dno' => 'DNo',
            'name' => '部门名称',
            'parentid' => '父级编号',
            'order' => 'Order',
        ];
    }

    public function getParent(){

        return $this->hasOne(GkyQyhDepartment::className(),['id'=>'parentid']);
    }

    public function getDeptUsers(){

        return $this->hasMany(GkyQyhDeptUser::className(),['dept_id'=>'id']);
    }

    public function getQyh(){

        return $this->hasOne(GkyQyh::className(),['id'=>'qyh_id']);
    }

    public static function findByNoAndCorpid($dno, $corpid){

        $qyh = GkyQyh::findByCorpid($corpid);

        return GkyQyhDepartment::find()
            ->where(['dno' => $dno,'qyh_id'=>$qyh->id])
            ->one();
    }

    /**
     * 从微信取部门信息并更新
     */
    public static function updataAll($corpid){

        $qyh = GkyQyh::findByCorpid($corpid);
        $options = array(
            'token'=>'gky',   //填写应用接口的Token
            'encodingaeskey'=>$qyh->aeskey,//填写加密用的EncodingAESKey
            'appid'=>$corpid,  //填写高级调用功能的appid
            'appsecret'=>$qyh->secret, //填写高级调用功能的密钥
        );

        $weObj = new QyWechat($options);
        $array = $weObj->getDepartment();
        if($array != false && $array['errcode'] == 0){
            foreach($array['department'] as $department){
                $qydept = GkyQyhDepartment::findByNoAndCorpid($department['id'],$qyh->corpid);
                if($qydept == null){
                    $qydept = new GkyQyhDepartment();
                    $qydept->id = $qyh->id.$department['id'];
                }
                $qydept->dno =  $department['id'];
                $qydept->name = $department['name'];
                $qydept->parentid = $qyh->id.$department['parentid'];
                $qydept->order = $department['order'];
                $qydept->qyh_id = $qyh->id;
                $qydept->save();
            }
        }
    }

    /**
     * 更新所有企业号的所有部门
     */
    public static function updataByAll(){
        $qyhs = GkyQyh::find()->all();
        foreach($qyhs as $qyh){
            GkyQyhDepartment::updataAll($qyh->corpid);
        }
    }

    /**
     * 查询所有部门，没有则从微信更新
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function findByAll($corpid){
        $qyh = GkyQyh::findByCorpid($corpid);
        $array = GkyQyhDepartment::find()->where(['qyh_id'=>$qyh->id])->all();
        if($array == null){
            GkyQyhDepartment::updataAll($corpid);
        }

        return GkyQyhDepartment::find()->where(['qyh_id'=>$qyh->id])->all();
    }

    /**
     * 查询所有部门成员，没有则从微信更新
     */
    public static function findMembers($corpid){
        $qyh = GkyQyh::findByCorpid($corpid);
        $depts = GkyQyhDepartment::find()->where(['qyh_id'=>$qyh->id])->all();
        if($depts == null){
            GkyQyhDepartment::updataAll($corpid);
            $depts = GkyQyhDepartment::find()->where(['qyh_id'=>$qyh->id])->all();
        }

        $results = [];
        foreach($depts as $dept){
            $result = [];
            $result['id'] = $dept->id;
            $result['dno'] = $dept->dno;
            $result['name'] = $dept->name;
            $result['parentid'] = $dept->parentid;
            $result['type'] = $dept->type;
            foreach($dept->deptUsers as $deptUser){
                $member = $deptUser->user;
                $result['members'][] = $member;
            }
            $results[] = $result;
        }

        return ArrayUtil::list_to_tree($results,'id','parentid','items',$qyh->id.'0');
    }

}
